<?php
namespace Manage\Controller;
use Think\Controller;

/**
 * Class AdminGateController
 * @package Manage\Controller
 * PC端河道闸门
 */
class AdminGateController extends Controller {

    private $model_name = 'Gate';
    private $record_model = 'GateRecord';

    public function all_view(){
        $this->display('all_view');
    }

    public function get_all_facilities(){
        $model = D($this->model_name);
        $gate_model = D('Gate');
        $weather_model = D('WeatherchangeLog');
        $list = $model->select();
        $return_array = array();
        foreach($list as $v){
            $temp = array();
            $temp['id'] = $v['id'];
            $temp['name'] = $v['gate_name'];
            $temp['gps'] = $v['gate_point'];
            $temp['weather'] = $weather_model->get_last_one(3, $v['id']);
            $temp['aa'] = $gate_model->q_s($v['id']);
            if($gate_model->q_s($v['id'])==-99)
                $temp['status'] = 99;
            else if($gate_model->q_s($v['id'])==-1)
                $temp['status'] = -1;
            else
                $temp['status'] = 1;
            $return_array[] = $temp;
        }
        echo json_encode($return_array);
    }

    public function index(){
        $duty_person = D('MobileAdmin')->getAll();
        $this->assign('duty_persons', $duty_person);
        $this->display();
    }

    public function get_all(){
        if(!I('get.gen')){
            $list = get_date_grid($this->model_name);
        }else{
            $map = array_merge(get_page_query_map(I('get.')), get_page_query_map(I('post.')));
            $page = max(I('get.page'), 1);
            $rows_num = get_kv_val('admin_page_list_num')?get_kv_val('admin_page_list_num'):I('get.rows');
            $list = D($this->model_name)->gen_search($map, $page, $rows_num);
        }
        echo json_encode($list);
    }

    public function add(){
        $model = D($this->model_name);
        if(IS_POST){
            $data = filterInput($_POST);
            $id = $model->addObj($data, 'id');
            echo json_encode(array('status'=>1, 'message'=>$id));
            return;
        }else if(IS_GET){

        }
        $this->display();
    }

    public function edit(){
        $model = D($this->model_name);
        if(IS_POST){
            $post_data = filterInput($_POST);
            $model->save($post_data);
//            $this->success(LANG('save_success'));
            echo json_encode(array('status'=>1, 'message'=>$post_data['id']));
            return;
        }else if(IS_GET){
            $data = filterInput($_GET);
            $item = $model->queryObj($data['id'], 'id');

            $this->assign('item', $item);
        }
        $this->display();
    }

    public function deleteArray(){
        $data = filterInput($_POST);
        $ids = $data['ids'];
        $model = D($this->model_name);
        $item = $model->deleteArray($ids);
        if($item){
            echo json_encode(array('status'=>1));
        }else{
            echo json_encode(array('status'=>0));
        }
    }

    public function log_index(){
        $this->display();
    }

    public function log_get_all(){
        $list = get_date_grid($this->record_model);
        echo json_encode($list);
    }

    public function log_add(){
        $model = D($this->record_model);
        if(IS_POST){
            $data = filterInput($_POST);
            $model->addObj($data, 'id');
            echo json_encode(array('status'=>1,'msg'=>'保存成功！'));
            return;
        }
    }

    public function log_edit(){
        $model = D($this->record_model);
        if(IS_POST){
            $post_data = filterInput($_POST);

            $model->save($post_data);
            echo json_encode(array('status'=>1, 'message'=>$post_data['id']));
            return;
        }
    }

    public function log_deleteArray(){
        $data = filterInput($_POST);
        $ids = $data['ids'];
        $model = D($this->record_model);
        $item = $model->deleteArray($ids);
        if($item){
            echo json_encode(array('status'=>1));
        }else{
            echo json_encode(array('status'=>0));
        }
    }

    public function visualization(){
        $pid = I('get.pid')?I('get.pid'):0;
        //查询出该泵站
        $this_station = D($this->model_name)->queryObj($pid, 'id');
        //查询出管理人员
        $admin_model = D('MobileAdmin');
        $admins = $admin_model->query_by_ids($this_station['gate_opr']);

        $this->assign('station', $this_station);
        $this->assign('admins', $admins);
        $this->display();
    }

    public function overview(){
        $id = I('get.id');
        $model = D($this->model_name);
        $cur = $model->queryObj($id, 'id');
        $this->assign('cur', $cur);
        $this->assign('gate', $cur);
        $this->display();
    }

    public function list_index(){
        $duty_person = D('MobileAdmin')->getAll();
        $this->assign('duty_persons', $duty_person);
        $this->display('temp');
    }

    public function get_river_gate_tree(){
        $model = D($this->model_name);
        echo json_encode($model->get_river_gate_tree());
    }

    public function get_gate_json(){
        $id = I('get.id');
        $obj = D($this->model_name)->queryObj($id, 'id');
        $obj['gate_opr_names'] = filter_id_to_ralname($obj['gate_opr']);
        echo $obj?json_encode($obj):json_encode(array('status'=> -1));
    }

    public function base_info(){
        $this->display();
    }

    public function river_gate(){
        $this->display();
    }

    public function river_gate_log(){
        $this->display('log_index');
    }

    public function get_obj_json(){
        $id = I('get.id');
        $obj = D($this->model_name)->queryObj($id, 'id');
        echo $obj?json_encode($obj):json_encode(array('status'=> -1));
    }

    public function get_obj_log_json(){
        $id = I('get.id');
        $obj = D($this->record_model)->queryObj($id, 'id');
        $station_model = D('Gate');
        $station = $station_model->queryObj($obj['gateid'], 'id');
        $obj['num'] = $station['gate_number'];
        $obj['station'] = $station['gate_name'];
        echo $obj?json_encode($obj):json_encode(array('status'=> -1));
    }

    public function get_all_gate(){
        $list = D($this->model_name)->getAll();
        echo json_encode($list);
    }

    public function weather_log(){
        $this->display();
    }

    public function log_show_gate_index(){
        if(!I('get.cc'))
            $this->display();
        else
            $this->display('log_show_gate_nocheck_index');
    }

    public function log_show_weather_index(){
        $this->display();
    }

    public function log_log_index(){
        if(!I('get.cc'))
            $this->display('log_opr');
        else
            $this->display('log_nocheck_opr');
    }

    public function set_check(){
        D($this->record_model)->checked_record(I('post.ids'));
        echo json_encode(array('status'=> 1));
    }

    public function get_all_combox(){
        $list = D($this->model_name)->field('id,gate_name as name')->select();
        $list = stations_add_all_text($list);
        echo json_encode($list);
    }

    public function just_see(){
        $this->display();
    }

    public function export_record(){
        header("Content-type: text/html; charset=utf-8");
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");
        $art = array(
            'station' => 'Gate',
            'pid_field' => 'id',
            'record_pid_field' => 'gateid',
            'sta_name_field' => 'gate_name',
        );
        $pid = I('get.pid')?I('get.pid'):0;
        $start = I('get.start')?I('get.start'):'2016-01-01 00:00:00';
        $end = I('get.end')?I('get.end'):'2016-12-31 00:00:00';
        $str = '((gate_start >= \''.$start.'\' AND gate_start <= \''.$end.'\') OR
        (gate_start <= \''.$start.'\' AND gate_off >= \''.$end.'\') OR
        (gate_off >= \''.$start.'\' AND gate_off <= \''.$end.'\')
        OR (gate_off is null AND gate_start <=  \''.$end.'\'))';
        $station_model = D($art['station']);
        $fy_model = D($this->model_name);
        $record_model = D($this->record_model);
        $temp_file = './excelfile/rivergate.xls';
        $out_file_name = '闸门运行记录';
        $php_reader = new \PHPExcel_Reader_Excel5();
        $filename = file_zh_cn_icvon($temp_file);
        if(!$php_reader->canRead($filename)){
            echo '无法识别的Excel文件！';
            return false;
        }
        $php_excel = $php_reader->load($filename);
        $pids = explode(',', $pid);
        $index = 0;
        foreach($pids as $pid){
            $station = $station_model->queryObj($pid, 'id');
            $new_sheet = new \PHPExcel_Worksheet($php_excel); //创建一个工作表
            $php_excel->addSheet($new_sheet); //插入工作表
            $php_excel->setActiveSheetIndex($index);
            $currentSheet = $php_excel->getActiveSheet($index);
            $currentSheet->setTitle($station['gate_name']);
            $start_row = 5;
            $row = $start_row;
            //先查找出该泵站的泵机，循环遍历泵机的记录，重复写入
            $station = $station_model->queryObj($pid, 'id');
            $fys = $fy_model->queryField($art['pid_field'],$station['id']);
            $currentSheet->setCellValue('A1',$station[$art['sta_name_field']].$out_file_name);
            $currentSheet->getColumnDimension('B')->setWidth(14);
            $currentSheet->getColumnDimension('C')->setWidth(20);
            $currentSheet->getColumnDimension('E')->setWidth(20);
            $currentSheet->getColumnDimension('F')->setWidth(14);
            $currentSheet->getColumnDimension('G')->setWidth(14);
            $currentSheet->getColumnDimension('H')->setWidth(14);
            $currentSheet->getColumnDimension('I')->setWidth(14);
            $currentSheet->mergeCells('A3:A4');
            $currentSheet->mergeCells('B3:B4');
            $currentSheet->mergeCells('D3:D4');
            $currentSheet->mergeCells('F3:F4');
            $currentSheet->mergeCells('G3:G4');
            $currentSheet->mergeCells('H3:H4');
            $currentSheet->mergeCells('I3:I4');
            $currentSheet->mergeCells('J3:J4');
            $currentSheet->mergeCells('K3:K4');
            $index_num = 1;
            $check_text = '';
            foreach($fys as $fy){
                $map[$art['record_pid_field']] = array('eq', $fy['id']);
                $list = $record_model->where($map)->where($str)->order('date desc')->select();
                $list = $record_model->bz_record($fy, $list, $start, $end);
                $check_text = records_check_status($list);
                foreach($list as $k => $record){
                    $currentSheet->setCellValue('A'.$row,$index_num++);
                    $currentSheet->setCellValue('B'.$row,$fy['gate_number']);
                    $currentSheet->setCellValue('C'.$row,$record['gate_start']);
                    $currentSheet->setCellValue('D'.$row,$record['gate_startwaterline']);
                    $currentSheet->setCellValue('E'.$row,$record['gate_off']);
                    $currentSheet->setCellValue('F'.$row,$record['gate_offwaterline']);
                    $currentSheet->setCellValue('G'.$row,round($record['time'],2));
//                $currentSheet->setCellValue('H'.$row,$record['weather']);
                    $currentSheet->setCellValue('I'.$row,$record['gate_height']);
                    $currentSheet->setCellValue('J'.$row,$record['opr']);
                    $currentSheet->setCellValue('K'.$row,$record['gate_reson']);
                    $row++;
                }
            }
            //设定一级表头
            $currentSheet->mergeCells('A1:K2');
            $currentSheet->setCellValue('A1', $station['gate_name'].'闸开启记录'.'('.$check_text.')');
            $currentSheet->getRowDimension(1)->setRowHeight(35);
            $currentSheet->getStyle('A1')->getFont()->setName('宋体');
            $currentSheet->getStyle('A1')->getFont()->setSize(24);
            $currentSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $currentSheet->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //设定二级表头
            $currentSheet->mergeCells('A3:A3');
            $currentSheet->setCellValue('A3', '序号');
            $currentSheet->mergeCells('B3:B3');
            $currentSheet->setCellValue('B3', '闸门编号');
            $currentSheet->mergeCells('C3:C3');
            $currentSheet->setCellValue('C3', '开闸时间');
            $currentSheet->setCellValue('C4', '(年.月.日-时间）');
            $currentSheet->mergeCells('D3:D3');
            $currentSheet->setCellValue('D3', '开闸时水位高度（米）');
            $currentSheet->mergeCells('E3:E3');
            $currentSheet->setCellValue('E3', '关闸时间');
            $currentSheet->setCellValue('E4', '(年.月.日-时间）');
            $currentSheet->mergeCells('F3:F3');
            $currentSheet->setCellValue('F3', '关闸时水位高度（米）');
            $currentSheet->mergeCells('G3:G3');
            $currentSheet->setCellValue('G3', '闸门开启时间（小时）');
            $currentSheet->mergeCells('H3:H3');
            $currentSheet->setCellValue('H3', '天气(雨）');
            $currentSheet->mergeCells('I3:I3');
            $currentSheet->setCellValue('I3', '开闸高度');
            $currentSheet->mergeCells('J3:J3');
            $currentSheet->setCellValue('J3', '操作人员');
            $currentSheet->mergeCells('K3:K3');
            $currentSheet->setCellValue('K3', '备注');
            $currentSheet->getStyle('A'.'1'.':L'.$row)->getFont()->setName('宋体');
            $currentSheet->getStyle('A'.'1'.':L'.$row)->getFont()->setSize(11);
            $currentSheet->getStyle('A'.'1'.':L'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $currentSheet->getStyle('A'.'1'.':L'.$row)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $currentSheet->getStyle('A1:L'.$row)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $index++;
        }

        $php_writer = new \PHPExcel_Writer_Excel5($php_excel);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        $out = substr($start,0,10).'/'.substr($end,0,10).'_'.$station[$art['sta_name_field']].$out_file_name;
        header("Content-Disposition: attachment;filename=".$out.".xls");
        header('Cache-Control: max-age=0');
        $php_writer->save('php://output');
    }

    public function import(){
        header("Content-type: text/html; charset=utf-8");
        $filename = '.'.I('get.file_path');
        $start_row = 2;
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        $php_reader = new \PHPExcel_Reader_Excel5();
        $filename = file_zh_cn_icvon($filename);
        $php_excel = $php_reader->load($filename);

        $model = D('PumpingStation');
        $excel_stations = array();
        $no_in_excel_stations = array();
        for($sheet_index=0;$sheet_index<1;$sheet_index++){
            $currentSheet = $php_excel->getSheet($sheet_index);
            $allRow = $currentSheet->getHighestRow();
            for($currentRow = $start_row;$currentRow <= $allRow;$currentRow++){
                $map['gate_name'] = array('eq', $currentSheet->getCell('A'.$currentRow)->getValue());
                $one = $model->where($map)->find();
                if($one||$currentSheet->getCell('A'.$currentRow)->getValue()==''){
                    continue;
                }
                $station_data = array();
                $station_data['gate_name'] = $currentSheet->getCell('A'.$currentRow)->getValue();
                $station_data['gate_number'] = $currentSheet->getCell('B'.$currentRow)->getValue();
                $station_data['gate_ctltype'] = $currentSheet->getCell('C'.$currentRow)->getValue();
                $station_data['gate_switsty'] = $currentSheet->getCell('D'.$currentRow)->getValue();
                $station_data['gate_address'] = $currentSheet->getCell('E'.$currentRow)->getValue();
                $station_data['gate_point'] = $currentSheet->getCell('F'.$currentRow)->getValue();
                $station_data['phone'] = $currentSheet->getCell('G'.$currentRow)->getValue();
                $station_data['gate_svcdt'] = $currentSheet->getCell('H'.$currentRow)->getValue();
                $station_data['gate_mrf'] = $currentSheet->getCell('I'.$currentRow)->getValue();
                $station_data['gate_model'] = $currentSheet->getCell('J'.$currentRow)->getValue();
                $station_data['note'] = $currentSheet->getCell('K'.$currentRow)->getValue();
                $station_data['gate_blev'] = $currentSheet->getCell('L'.$currentRow)->getValue();
                $station_data['gate_wid'] = $currentSheet->getCell('M'.$currentRow)->getValue();
                $station_data['gate_h'] = $currentSheet->getCell('N'.$currentRow)->getValue();
                $station_data['gate_rownum'] = $currentSheet->getCell('O'.$currentRow)->getValue();
                $station_data['gate_holenum'] = $currentSheet->getCell('P'.$currentRow)->getValue();
                $station_data['gate_motorpower'] = $currentSheet->getCell('Q'.$currentRow)->getValue();
                $model->add($station_data);
            }
        }
        echo '导入完成';
    }

    public function export(){
        header("Content-type: text/html; charset=utf-8");
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");
        $temp_file = './exportexcel/river_gate.xls';
        $php_reader = new \PHPExcel_Reader_Excel5();
        $filename = file_zh_cn_icvon($temp_file);
        if(!$php_reader->canRead($filename)){
            echo '无法识别的Excel文件！';
            return false;
        }
        $php_excel = $php_reader->load($filename);
        $currentSheet = $php_excel->getSheet(0);
        $model = D('PumpStation');
        $list = $model->getAll();
        $currentRow = 2;
        foreach($list as $station_data){
            $currentSheet->setCellValue('A'.$currentRow, $station_data['gate_name']);
            $currentSheet->setCellValue('B'.$currentRow, $station_data['gate_number']);
            $currentSheet->setCellValue('C'.$currentRow, gate_cont_type_option($station_data['gate_ctltype'], false));
            $currentSheet->setCellValue('D'.$currentRow, gate_swit_sty_option($station_data['gate_switsty'], false));
            $currentSheet->setCellValue('E'.$currentRow, $station_data['gate_address']);
            $currentSheet->setCellValue('F'.$currentRow, $station_data['gate_point']);
            $currentSheet->setCellValue('G'.$currentRow, $station_data['phone']);
            $currentSheet->setCellValue('H'.$currentRow, $station_data['gate_svcdt']);
            $currentSheet->setCellValue('I'.$currentRow, $station_data['gate_mrf']);
            $currentSheet->setCellValue('J'.$currentRow, $station_data['gate_model']);
            $currentSheet->setCellValue('K'.$currentRow, $station_data['note']);
            $currentSheet->setCellValue('L'.$currentRow, $station_data['gate_blev']);
            $currentSheet->setCellValue('M'.$currentRow, $station_data['gate_wid']);
            $currentSheet->setCellValue('N'.$currentRow, $station_data['gate_h']);
            $currentSheet->setCellValue('O'.$currentRow, $station_data['gate_rownum']);
            $currentSheet->setCellValue('P'.$currentRow, $station_data['gate_holenum']);
            $currentSheet->setCellValue('Q'.$currentRow, $station_data['gate_motorpower']);
            $currentRow++;
        }
        $currentSheet->getStyle('A1:N'.$currentRow)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $currentSheet->getStyle('A1:N'.$currentRow)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getStyle('A1:N'.$currentRow)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        $php_writer = new \PHPExcel_Writer_Excel5($php_excel);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=河道闸门.xls");
        header('Cache-Control: max-age=0');
        $php_writer->save('php://output');
    }
}